<?php

namespace Part02_StrategyMode\Code5;

require_once '../../autoload.php';

/**
 * 假设3个商品，实际开发不可能这么传入，但问题不大，我们学的是设计模式不是业务。
 */
$goodsAName = $_POST['goodsAName'];
$goodsAPrice = $_POST['goodsAPrice'];
$goodsANum = $_POST['goodsANum'];
$chooseAType = $_POST['AType'];

$goodsBName = $_POST['goodsBName'];
$goodsBPrice = $_POST['goodsBPrice'];
$goodsBNum = $_POST['goodsBNum'];
$chooseBType = $_POST['BType'];

$goodsCName = $_POST['goodsCName'];
$goodsCPrice = $_POST['goodsCPrice'];
$goodsCNum = $_POST['goodsCNum'];
$chooseCType = $_POST['CType'];

/**
 * 传入不同的策略获得不同的结果
 */
try {
    $totalA = getCashObj($chooseAType)->GetResult($goodsAPrice * $goodsANum);
    $totalB = getCashObj($chooseBType)->GetResult($goodsBPrice * $goodsBNum);
    $totalC = getCashObj($chooseCType)->GetResult($goodsCPrice * $goodsCNum);
} catch (Exception $e) {
    echo $e->getMessage();
    die;
}

$total = $totalA + $totalB + $totalC;

$list[$goodsAName] = [
    'price' => $goodsAPrice,
    'num' => $goodsANum,
    'total' => $totalA,
    'type' => $chooseAType,
];
$list[$goodsBName] = [
    'price' => $goodsBPrice,
    'num' => $goodsBNum,
    'total' => $totalB,
    'type' => $chooseBType,
];
$list[$goodsCName] = [
    'price' => $goodsCPrice,
    'num' => $goodsCNum,
    'total' => $totalC,
    'type' => $chooseCType,
];

foreach ($list as $goodsName => $data) {
    echo sprintf("%s：单价%d元,数量%d个,折扣情况【%s】总价%d元\n", $goodsName, $data['price'], $data['num'], $data['type'], $data['total']);
}
echo '总价为：' . $total . '元';


/**
 * @throws \Exception
 */
function getCashObj($type)
{
    switch ($type) {
        case '正常收费':
            return new CashContext(new CashNormal());
        case '满300返100':
            return new CashContext(new CashReturn(300, 100));
        case '打8折':
            return new CashContext(new CashRebate(0.8));
        default:
            throw new Exception('未知折扣');
    }
}